package com.yunji.hushuang.plugin;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author hushuang
 * @since 2019/10/06
 */
public class Plugin implements InvocationHandler {

    private final Object target;
    private final Interceptor interceptor;
    private final Map<Class<?>, Set<Method>> signatureMap;

    private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
        this.target = target;
        this.interceptor = interceptor;
        this.signatureMap = signatureMap;
    }

    public static Object wrap(Object target, Interceptor interceptor) {
        // 创建代理
        Class<?> type = target.getClass();
        Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
        Class<?>[] interfaces = getAllInterfaces(type, signatureMap);

        if (interfaces.length > 0) {
            return Proxy.newProxyInstance(
                    type.getClassLoader(),
                    interfaces,
                    new Plugin(target, interceptor, signatureMap));
        }
        return target;
    }

    private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
        Class<?> type = interceptor.getClass();
        Intercepts intercepts = type.getAnnotation(Intercepts.class);
        if (intercepts == null) {
            throw new RuntimeException("intercepts");
        }
        Map<Class<?>, Set<Method>> signatureMap = new HashMap<>();
        Signature[] signatures = intercepts.value();
        for (Signature signature : signatures) {
            Set<Method> methods = signatureMap.computeIfAbsent(signature.type(), k -> new HashSet<>());
            try {
                if (!signature.type().isInterface()) {
                    System.out.println(signature.type() + " is not a interface");
                }
                methods.add(signature.type().getMethod(signature.method(), signature.args()));
            } catch (NoSuchMethodException e) {
                throw new RuntimeException("Could not find method on " + signature.type() + " named " + signature.method() + ". Cause: " + e, e);
            }
        }

        return signatureMap;
    }

    private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
        Set<Class<?>> interfaces = new HashSet<>();
        while (type != null) {
            for (Class<?> clazz : type.getInterfaces()) {
                if (signatureMap.containsKey(clazz)) {
                    interfaces.add(clazz);
                }
            }
            type = type.getSuperclass();
        }
        return interfaces.toArray(new Class<?>[0]);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Set<Method> methods = signatureMap.get(method.getDeclaringClass());
        if (methods != null && methods.contains(method)) {
            return interceptor.intercept(new Invocation(target, method, args));
        }
        return method.invoke(target, args);
    }
}
